package com.example.administrator.wallet.view.activity.find.cointrans;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.androidkun.xtablayout.XTabLayout;
import com.blankj.utilcode.util.ActivityUtils;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Constant;
import com.example.administrator.wallet.custom.MyWebSocketService;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.fragment.quotation.BuyTransactionDetailsFragment;
import com.example.administrator.wallet.view.fragment.quotation.CoinCurrentDelegateFragment;
import com.example.administrator.wallet.view.fragment.quotation.SellTransactionDetailsFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class CoinTransactionDetailsActivity extends BaseActivity {

    @Bind(R.id.finish_img)
    ImageButton ibBack;
    @Bind(R.id.view_title)
    TextView tvTitle;
    @Bind(R.id.tab_layout_activity_coin_transaction_details)
    XTabLayout table;
    @Bind(R.id.viewpager_activity_coin_transaction_detail)
    ViewPager viewPager;
    @Bind(R.id.iv_more_record_toolbar)
    ImageView ivMoreRecord;
    @Bind(R.id.iv_k_line_toolbar)
    ImageView ivKLine;
    @Bind(R.id.iv_add_to_self_toolbar)
    ImageView ivAddToSelf;

    private List<String> tabData;
    private List<Fragment> pagerData;

    private MyWebSocketService myWebSocketService;
    private ServiceConnection serviceConnection;

    String token;
    private String title;
    private String stock;
    private String money;

    @Override
    public void init() {
        initView();
        initData();
        initAdapter();
    }

    private void initView() {

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myWebSocketService = ((MyWebSocketService.ServiceBinder) service).getService();
                myWebSocketService.join();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        bindService(new Intent(this,MyWebSocketService.class),serviceConnection, Context.BIND_AUTO_CREATE);

    }

    private void initData() {

        token = SharedPrefsUtil.getValue(this,"wallet","token","");

        Intent intent = getIntent();
        title = intent.getStringExtra(Constant.TO_COIN_TRANSACTION_DETAILS_TITLE);
        tvTitle.setText(title);

        String[] markets = title.split("/");

        stock = markets[0];
        money = markets[1];

        tabData = new ArrayList<>();
        pagerData =new ArrayList<>();
        tabData.clear();
        pagerData.clear();


        tabData.add(getString(R.string.Buy));
        tabData.add(getString(R.string.Sell));
        tabData.add(getString(R.string.current_commission));

        Bundle buyBundle = new Bundle();
        buyBundle.putString("toBuyTransactionFragment", money);
        buyBundle.putString("toBuyTransactionFragmentMarket", stock + money);
        BuyTransactionDetailsFragment buyFragment = new BuyTransactionDetailsFragment();
        buyFragment.setArguments(buyBundle);
        pagerData.add(buyFragment);

        Bundle sellBundle = new Bundle();
        sellBundle.putString("toSellTractionFragment", stock);
        sellBundle.putString("toSellTractionFragmentMarket", stock + money);
        SellTransactionDetailsFragment sellFragment = new SellTransactionDetailsFragment();
        sellFragment.setArguments(sellBundle);
        pagerData.add(sellFragment);

        Bundle currentDelegate = new Bundle();
        currentDelegate.putString("toCurrentDelegationFragment",stock + money);
        CoinCurrentDelegateFragment currentDelegateFragment = new CoinCurrentDelegateFragment();
        currentDelegateFragment.setArguments(currentDelegate);
        pagerData.add(currentDelegateFragment);


    }

    public int sendMeessage(String method, JSONArray jsonArray){
        int id = myWebSocketService.sendMessage(method,jsonArray);
        return id;
    }

    private void initAdapter() {
        MyFragmentPagerAdapter adapter=new MyFragmentPagerAdapter(this,tabData,pagerData);
        viewPager.setAdapter(adapter);
        table.setupWithViewPager(viewPager);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_coin_transaction_details;
    }

    @OnClick({R.id.finish_img,R.id.iv_more_record_toolbar,R.id.iv_k_line_toolbar,R.id.iv_add_to_self_toolbar})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.finish_img:
                finish();
                break;
            case R.id.iv_more_record_toolbar:
                View popView = View.inflate(this,R.layout.popup_record,null);
                Button btnTransactionRecords = (Button) popView.findViewById(R.id.btn_transaction_records_popup_record);
                Button btnCancel = (Button) popView.findViewById(R.id.btn_cancel_popup_record);

                final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setFocusable(true);
                popupWindow.setTouchable(true);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                popupWindow.setOutsideTouchable(true);
                popupWindow.update();
                View parent = LayoutInflater.from(this).inflate(R.layout.activity_coin_transaction_details, null);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);//适配虚拟按键
                popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
                //popupWindow在弹窗的时候背景半透明
                final WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 0.5f;
                getWindow().setAttributes(params);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params.alpha = 1.0f;
                        getWindow().setAttributes(params);
                    }
                });

                btnTransactionRecords.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(CoinTransactionDetailsActivity.this,MarketTransactionRecodsActivity.class);
                        intent.putExtra(Constant.TO_MARKET_TRANSACTION_RECORDS_ACTIVITY,title);
                        ActivityUtils.startActivity(intent);
                        popupWindow.dismiss();
                    }
                });

                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                break;
            case R.id.iv_k_line_toolbar:
                Intent intent =new Intent(this,CoinTransactionDetailsKLineActivity.class);
                intent.putExtra(Constant.TO_KLINE_ACTIVITY_TITLE,title);
                startActivity(intent);
                break;
            case R.id.iv_add_to_self_toolbar:

                break;
        }

    }

    public static class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        private List<String> tab_datas;
        private List<Fragment> pager_datas;

        public MyFragmentPagerAdapter(CoinTransactionDetailsActivity coinTransactionDetailsActivity, List<String> tab_datas, List<Fragment> pager_datas) {
            super(coinTransactionDetailsActivity.getSupportFragmentManager());
            this.tab_datas=tab_datas;
            this.pager_datas=pager_datas;
        }

        @Override
        public int getCount() {
            return tab_datas.size();
        }

        @Override
        public Fragment getItem(int position) {
            return pager_datas.get(position);
        }



        @Override
        public CharSequence getPageTitle(int position) {
            return tab_datas.get(position);
        }
    }
}
